package com.gitee.xmhzzz.component.shutdown.graceful.rocketmq;

import com.gitee.xmhzzz.component.shutdown.graceful.event.ApplicationShutdownEvent;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.support.DefaultRocketMQListenerContainer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.EventListener;

import java.util.Map;

/**
 * @ClassName RocketMqShutdown
 * @Description
 * @Author wzq
 * @Date 2023/9/25 13:40
 * @Version 1.0
 */
@Slf4j
@ConditionalOnProperty(value = "xmhzzz.graceful.shutdown.enable", havingValue = "true")
public class RocketMqShutdown {
    private volatile boolean shutdown = false;


    @EventListener
    public void shutdownEventListener(ApplicationShutdownEvent applicationEvent) {
        try {
            if (!this.shutdown) {
                this.shutdown = true;
                long beginTime = System.currentTimeMillis();
                log.info("rocketmq start beginTime [{}]", beginTime);
                ApplicationContext applicationContext = (ApplicationContext) applicationEvent.getSource();
                // 获取当前应用所有消费者
                Map<String, DefaultRocketMQListenerContainer> map = applicationContext
                        .getBeansOfType(DefaultRocketMQListenerContainer.class);
                for (Map.Entry<String, DefaultRocketMQListenerContainer> next : map.entrySet()) {
                    DefaultRocketMQListenerContainer listener = next.getValue();
                    listener.destroy();
                }
                Long endTime = System.currentTimeMillis() - beginTime;
                log.info("rocketmq  shutdown time [{}](ms)", endTime);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }
}
